import React from 'react';
import { inject, observer } from 'mobx-react';
import { Spin, Button, Modal, Tooltip, Row, Col, Tabs } from 'antd';
import {
    WeaReqTop,
    WeaAlertPage,
    WeaLeftRightLayout,
    WeaRightMenu,
    WeaNewScroll,
    WeaSearchGroup,
    WeaLocaleProvider,
    WeaBrowser,
    WeaTab
} from 'ecCom';
import LeftCom from './leftCom'
import Header from './head'
import PlanAndSummary from './planAndSummary'
import PlanLog from './operationLog'
import Feedback from './feedback'
import PlanShare from './planShare'
import RelateFiles from './relatedFiles'
import { getParams, getCurrentHeight, setWindowKeys } from '../../../util/Util';
const TabPane = Tabs.TabPane;
const getLabel = WeaLocaleProvider.getLabel;
const toJS = mobx.toJS;
const confirm = Modal.confirm;
@inject('planViewStore')
@observer
export default class Index extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            _height: getCurrentHeight(),//页面高度
            showLeft: false,//是否显示左侧抽屉
            topTab: [
                {
                    title: getLabel('516163', '总结计划'),
                    viewcondition: "1"
                },
                {
                    title: getLabel('22194', '相关附件'),
                    viewcondition: "2"
                },
                {
                    title: getLabel('509020', '报告共享'),
                    viewcondition: "3"
                },
                {
                    title: getLabel('33956', '意见反馈'),
                    viewcondition: "4"
                },
                {
                    title: getLabel('32061', '操作日志'),
                    viewcondition: "5"
                }
            ]
        };
        this.store = this.props.planViewStore
    }
    render() {
        const { _height, topTab } = this.state
        const { loading,cubeLoading, iscube,isSaved, noDataMessage, tabKey,planid } = this.store
        return (<div
            className="wea-workrelate-plan-report-view-container"
            onClick={this.onContextClick}
        >
            <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@o2ajvw`}
                datas={this.getMenus().rightMune}
                showUrlItem={false}
                style={{ height: '100%' }}
                collectParams={{
                    favname: getLabel('6015','我的报告'),
                    favouritetype: 5,
                    link: '/spa/workrelate/static/index.html?#/main/workrelate/plan/planIndex?menutype=1&planid='+ (planid?planid:""),
                    importantlevel: 1,
                }}
            >
                <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@2hwu5p`} spining={loading || (iscube == '1' && cubeLoading)  }>
                    <WeaReqTop ecId={`${this && this.props && this.props.ecId || ''}_WeaReqTop@l5ajyv`} {...this.getWeaReqTopConfig()} >
                        <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@2zmm8q`}
                            isNew={true}
                            leftWidth={220}
                            leftCom={<div ><LeftCom ecId={`${this && this.props && this.props.ecId || ''}_LeftCom@is9fw1`}></LeftCom></div>}
                            showLeft={this.state.showLeft}
                            onCollapse={showLeft => this.setState({ showLeft })}
                        >
                            {/* 日期选择 及 状态显示区域 */}
                            <Header ecId={`${this && this.props && this.props.ecId || ''}_Header@lp5ode`}></Header>
                            {noDataMessage && this.alertPage()}
                            {/* tab */}
                            {
                                noDataMessage == '' &&<div>
                                <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@o86u0u`}
                                    datas={this.getTopTab()}
                                    keyParam="viewcondition" //主键
                                    selectedKey={tabKey} Ï
                                    onChange={v => {this.store.setValue('tabKey', v);if(v=='3'){this.store.getShareSearch()}}}
                                />
                            {tabKey == '1' && <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@dal57w`} height={_height - 180}>
                                <PlanAndSummary ecId={`${this && this.props && this.props.ecId || ''}_PlanAndSummary@5k4hf9`} />
                            </WeaNewScroll>}
                            {tabKey == '2' && <RelateFiles ecId={`${this && this.props && this.props.ecId || ''}_RelateFiles@qef08m`} />}
                            {tabKey == '3' && isSaved && <PlanShare ecId={`${this && this.props && this.props.ecId || ''}_PlanShare@cj8fxg`} shareRef={this.refs.share} />}
                            {tabKey == '4' && isSaved && <Feedback ecId={`${this && this.props && this.props.ecId || ''}_Feedback@s540bs`} />}
                            {tabKey == '5' && isSaved && <PlanLog ecId={`${this && this.props && this.props.ecId || ''}_PlanLog@3gqchj`} />}
                            </div>
                            }
                            {this.buildShareBrowser()}
                        </WeaLeftRightLayout>
                    </WeaReqTop>
                </Spin>
            </WeaRightMenu>
        </div>)
    }
    componentWillMount() {
        this.init()
    }
    init = () => {
        //一些初始化请求
        this.store.setValue("type1","1")
        this.store.setValue("type2","")
        //如果是从其他地方跳转过来的
        let params = {};
        //如果url中有planid
        if (getParams('planid')) {
            params.planid = getParams('planid');
        } else if (getParams('resourceid')) {
            this.store.resourceid = getParams('resourceid');
            this.store.resourcetype = 4;
            params.type1 = getParams('type1');
            params.type2 = getParams('type2');
            params.year = getParams('year');
            params.resourceid = getParams('resourceid');
            params.resourcetype = 4;
            this.store.onDateChange('year', getParams('year'), true)
            this.store.setValue("tabSelectKey", params.type1)
            this.store.onDateChange('type2', parseInt(getParams('type2')), true)
        }
        this.store.setValue("locationkey", new Date().getTime())
        this.store.getPlanView(params);
        //清空日志请求长度
        this.store.setValue('planLog', {
            datas: [],
            lastcount: 0,
            lastid: '',
            status: '',
        })
        //设置windowkey
        setWindowKeys("1", getLabel('6015', '我的报告'));

        this.setState({ tabKey: '1' })
    }


    buildShareBrowser = () => {
        const { shareidsList, editshare } = this.store
        let _ = this
        //隐藏起来，只用ref的方式用按钮操作
        return <div style={{ display: 'none' }}><WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@l1pcjc`}
            ref="share"
            memorise
            title={getLabel('119', '共享')}
            viewAttr={editshare ? '2' : '1'}
            replaceDatas={toJS(this.store.shareidsList)}
            type={17}
            onChange={(ids, names, datas) =>
                _.onShareBrowerChange(ids, names, datas)}
            isSingle={false}
        /></div>
    }
    alertPage = () => {
        const { noDataMessage } = this.store
        return <div style={{ position: 'relative', height: 230 }}>
            <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@3ksnzm`} >
                <div style={{ color: '#F00' }}>
                    {noDataMessage}
                </div>
            </WeaAlertPage>
        </div>
    }
    //点击下属调用方法
    onSubClick(id, name) {
        this.store.resourceid = id;
        this.store.resourcename = name;
        this.store.resourcetype = 4;
        this.store.getPlanView();
        this.store.resetTabKey()
    };
    //点击页面时
    onContextClick = () => {
        this.store.toggleMonthWeekSelectComDisplayKey()
    };
    componentDidUpdate() {
        if(location.href.indexOf("/main/workrelate/plan/planView")>-1){
            const {  resourcename, planname } = this.store
            document.title= planname ;
        }
    }

    //顶部top组件设置
    getWeaReqTopConfig = () => {
        const { tabDatas, tabDatasLength, resourcename, planname } = this.store
        const title =  planname
        return {
            title,
            icon: <i className="icon-coms-implement" />,
            iconBgcolor: 'rgb(150, 53, 138)',
            loading: this.store.loading,
            buttons: this.getMenus().topButtons,
            showDropIcon: true,
            dropMenuDatas: this.getMenus().rightMune,
            //onDropMenuClick:this.onDropMenuClick,
            tabDatas: tabDatas,
            selectedKey: this.store.tabSelectKey,
            onChange: this.store.tabChange,
        };
    };
    //操作事件
    doOperation = operation => {
        this.setState({ operation });
        let _this = this;
        if (operation == 'save') {
            if (this.store.uploading) {
                this.fileCom.doUpload(operation);
            } else {
                this.store.doOperation(operation);
            }
        }

        if (operation == 'submit') {
            confirm({
                title: getLabel('508972', '确认提示'),
                content: getLabel('509013', '确认提交此报告吗？'),
                onOk() {
                    if (
                        (operation == 'submit') && _this.store.uploading
                    ) {
                        _this.fileCom.doUpload(operation);
                    } else {
                        _this.store.doOperation(operation);
                    }
                },
                onCancel() { },
            });
        }

        if (operation != 'save' && operation != 'submit') {
            this.store.doOperation(operation, this.props.getNoAuditCount);
        }
    };
    //生成右键菜单
    makeRightMenu = (
        key,
        content,
        onClick,
        iconClassName = 'icon-coms-search'
    ) => {
        return {
            key: key,
            icon: <i className={iconClassName} />,
            content: content,
            onClick: onClick,
        };
    };
    //获取菜单（右键和顶部）
    getMenus = () => {
        const { canedit, candel, canaudit, canreset, editshare, planstatus} = this.store;
        let rightMune = [];
        let topButtons = [];
        if (canreset &&!canedit) {
            rightMune.push(
                this.makeRightMenu(
                    '3',
                    getLabel('509014', '重新编写'),
                    () => {
                        this.doOperation('reset');
                    },
                    'icon-coms-top'
                )
            );
            topButtons.push(
                <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@4vbhsm@rewrite`} title={getLabel('509015', '重新编写计划报告')}>
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@44azek@rewrite`}
                        type="primary"
                        style={{ display: canreset ? '' : 'none' }}
                        onClick={() => this.doOperation('reset')}
                    >
                        {getLabel('509014', '重新编写')}
                    </Button>
                </Tooltip>
            );
        }
        if (canedit) {
            rightMune.push(
                this.makeRightMenu(
                    '0',
                    getLabel('86', '保存'),
                    () => {
                        this.doOperation('save');
                    },
                    'icon-coms-Save-as'
                )
            );
            rightMune.push(
                this.makeRightMenu(
                    '1',
                    getLabel('615', '提交'),
                    () => {
                        this.doOperation('submit');
                    },
                    'icon-coms-top'
                )
            );
            topButtons.push(
                <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@lkec0a@save`} title={getLabel('508724', '保存为草稿')}>
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@f12ag2@save`}
                        type="primary"
                        style={{ display: canedit ? '' : 'none' }}
                        onClick={() => this.doOperation('save')}
                    >
                        {getLabel('86', '保存')}
                    </Button>
                </Tooltip>
            );
            topButtons.push(
                <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@vtymso@submit`} title={getLabel('382335', '保存并提交')}>
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vzvc6w@submit`}
                        type="primary"
                        style={{ display: canedit ? '' : 'none' }}
                        onClick={() => this.doOperation('submit')}
                    >
                        {getLabel('615', '提交')}
                    </Button>
                </Tooltip>
            );
        }
        if (candel) {
            rightMune.push(
                this.makeRightMenu(
                    '2',
                    getLabel('91', '删除'),
                    () => {
                        this.doOperation('del');
                    },
                    'icon-coms-delete'
                )
            );
            topButtons.push(
                <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@m2plom@delete`} title={getLabel('509016', '删除此计划报告')}>
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@hj4uap@delete`}
                        type="primary"
                        style={{ display: candel ? '' : 'none' }}
                        onClick={() => this.doOperation('del')}
                    >
                        {getLabel('91', '删除')}
                    </Button>
                </Tooltip>
            );
        }

        if (canaudit) {
            rightMune.push(
                this.makeRightMenu(
                    '5',
                    getLabel('142', '批准'),
                    () => this.doOperation('approve'),
                    'icon-coms-Approval'
                )
            );
            rightMune.push(
                this.makeRightMenu(
                    '6',
                    getLabel('236', '退回'),
                    () => this.doOperation('return'),
                    'icon-coms-go-back'
                )
            );
            topButtons.push(
                <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@oo6zby@approve`} title={getLabel('509017', '批准计划报告')}>
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@lermiz@approve`}
                        type="primary"
                        style={{ display: canaudit ? '' : 'none' }}
                        onClick={() => this.doOperation('approve')}
                    >
                        {getLabel('142', '批准')}
                    </Button>
                </Tooltip>
            );
            topButtons.push(
                <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@5p6ih1@return`} title={getLabel('509018', '退回计划报告')}>
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@o0ap71@return`}
                        type="primary"
                        style={{ display: canaudit ? '' : 'none' }}
                        onClick={() => this.doOperation('return')}
                    >
                        {getLabel('236', '退回')}
                    </Button>
                </Tooltip>
            );
        }

        let menus = {
            topButtons,
            rightMune,
        };

        return menus;
    };
    onShareBrowerChange = (ids, names, datas) => {
        this.store.setPlanShare(ids, datas);
    };
    getTopTab = ()=>{
        const {topTab} = this.state
        const {isSaved,fileNum} = this.store
        topTab[1].title = `${getLabel('22194', '相关附件')} (${fileNum})`

        if(isSaved){
            return topTab
        }else{
            return [topTab[0],topTab[1]]
        }

    }
}
